package com.lungle.warmdiary.app.view.testcampaign.view;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.model.event.CampaignDetailShareEvent;
import com.lungle.warmdiary.app.model.response.CampaignComment;
import com.lungle.warmdiary.app.model.response.CampaignMycomment;
import com.lungle.warmdiary.app.model.response.Comment;
import com.lungle.warmdiary.app.utils.FileUtils;
import com.lungle.warmdiary.app.utils.LogUtils;
import com.lungle.warmdiary.app.utils.ShareUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by zhangxueyuan on 16/10/10.
 * <p>
 * 分享弹窗
 */
public class SharePopupWindow extends PopupWindow {
    private View mMenuView;

    private LinearLayout mGallery;

    private List<ShareItem> shareList = new ArrayList<>();
    private LayoutInflater mInflater;
    private Context context;
    private List<String> imageFile = new ArrayList<>();

    String shareTitle;
    String shareContent;
    String shareUrl;
    List<String> images;

    public SharePopupWindow(final Activity context, CampaignComment comment) {
        super(context);
        mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = mInflater.inflate(R.layout.share_layout, null);
        this.context = context;
        shareContent = comment.getContent();
        shareUrl = comment.getShareLink();
        images = comment.getImages();
        shareTitle = comment.getShareLinkTitle();
        setPopwindow();
    }


    public SharePopupWindow(final Activity context, CampaignMycomment campaignMycomment) {
        super(context);
        mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = mInflater.inflate(R.layout.share_layout, null);
        this.context = context;
        shareContent = campaignMycomment.getContent();
        shareUrl = campaignMycomment.getShortLink();
        images = campaignMycomment.getImages();
        shareTitle = campaignMycomment.getShareLinkTitle();
        setPopwindow();

    }

    public SharePopupWindow(final Activity context, Comment comment) {
        super(context);
        mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = mInflater.inflate(R.layout.share_layout, null);
        this.context = context;

        //// TODO: 16/10/15
        shareContent = comment.getContent();
        LogUtils.printLogD(comment.getContent());
        shareUrl = comment.getSharelink();
        images = comment.getImages();
        shareTitle = comment.getSharelinkTitle();
        setPopwindow();

    }

    private void setPopwindow() {
        initData();
        initView();

        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
//        this.setAnimationStyle(R.style.AnimBottom);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        for (String s : images) {
            LogUtils.printLogD("iamges:" + s);
        }
    }


    private void initData() {


        String s = AppContext.getInstance().getShare();

        LogUtils.printLogD("getShare:" + s);

        shareList.add(new ShareItem(0, "微信好友", R.drawable.weixin));
        shareList.add(new ShareItem(1, "QQ好友", R.drawable.qq));
        shareList.add(new ShareItem(2, "微信朋友圈", R.drawable.weixin_cicrle));
        shareList.add(new ShareItem(3, "新浪微博", R.drawable.weibo));
        shareList.add(new ShareItem(4, "QQ空间", R.drawable.qzone));

        if (!TextUtils.isEmpty(s)) {
            for (int j = 0; j < s.length(); j++) {
                //不存在
                if ('0' == s.charAt(j)) {
                    shareList.get(j).setVisiable(false);
                }
            }
        }
    }

    private void initView() {

        mGallery = (LinearLayout) mMenuView.findViewById(R.id.share_item);

        for (int i = 0; i < shareList.size(); i++) {
            if (shareList.get(i).isVisiable()) {
                View view = mInflater.inflate(R.layout.share_item,
                        mGallery, false);
                ImageView img = (ImageView) view
                        .findViewById(R.id.share_image);
                img.setImageResource(shareList.get(i).getImgId());
                TextView txt = (TextView) view
                        .findViewById(R.id.share_name);
                txt.setText(shareList.get(i).getName());
                mGallery.addView(view);
                final int num = i;
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        share(num);
                    }
                });
            }
        }

        mMenuView.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        mMenuView
                .findViewById(R.id.copy)
                .setOnClickListener(
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                if (Build.VERSION.SDK_INT >= 11) {
                                    ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                                    ClipData clipData = ClipData.newPlainText("publicId", String.format("%s\n%s：%s", shareContent, shareTitle, shareUrl));
                                    clipboardManager.setPrimaryClip(clipData);
                                } else {
                                    //noinspection deprecation
                                    android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                                    clipboardManager.setText(String.format("%s\n%s：%s", shareContent, shareTitle, shareUrl));
                                }
                                AppContext.showToastShort("复制成功");
                                dismiss();
                            }
                        }
                );
    }

    //todo 数字限制和url;
    private void share(int id) {
        if (id == 2) {
            downloadPictures(images, 2);
        } else if (id == 3) {
            downloadPictures(images, 3);
        } else {
            EventBus.getDefault().post(new CampaignDetailShareEvent(id));
        }
        dismiss();
    }

    static class ShareItem {
        int id;
        String name;
        int imgId;
        boolean visiable = true;

        public ShareItem(int id, String name, int imgId) {
            this.id = id;
            this.name = name;
            this.imgId = imgId;
        }

        public String getName() {
            return name;
        }

        public int getImgId() {
            return imgId;
        }

        public int getId() {
            return id;
        }

        public boolean isVisiable() {
            return visiable;
        }

        public void setVisiable(boolean visiable) {
            this.visiable = visiable;
        }
    }

    private void downloadPictures(List<String> pictures, int id) {
        Observable.from(pictures).subscribe(new Action1<String>() {
            @Override
            public void call(String url) {
                download(url, id);
            }
        });

    }

    private void download(String url, int id) {
        ApiFactory.getFileApi().downloadPicture(url).subscribeOn(Schedulers.io())
                .map(new Func1<ResponseBody, String>() {
                    @Override
                    public String call(ResponseBody responseBody) {
                        InputStream is = responseBody.byteStream();
                        String[] urlArr = url.split("/");
                        File filesDir = Environment.getExternalStorageDirectory();
                        File file = new File(filesDir, urlArr[urlArr.length - 1]);
                        if (file.exists()) file.delete();
                        try {
                            FileUtils.writeFile(file, is);
                            return file.getAbsolutePath();
                        } catch (IOException e) {

                        }
                        return null;
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                if (imageFile.size() >= images.size()) {
                    if (id == 2) {
                        ShareUtils.share9PicsToWXCircle(context, String.format("%s\n%s：%s", shareContent, shareTitle, shareUrl), imageFile);
                    } else if (id == 3) {
                        if (shareContent.length() > 120)
                            ShareUtils.share9PicsToWeibo(context, String.format("%s %s", shareContent.substring(0, 120), shareUrl), imageFile);
                        else
                            ShareUtils.share9PicsToWeibo(context, String.format("%s %s", shareContent, shareUrl), imageFile);

                    }
                    imageFile.clear();
                }
            }

            @Override
            public void onError(Throwable e) {
                AppContext.showToast(e.getMessage());
            }

            @Override
            public void onNext(String path) {
                if (path != null) {
                    imageFile.add(path);
                }
            }

        });


    }
}
